import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

// 路由组件懒加载
const Login = () => import('@/views/Login.vue')
const MainLayout = () => import('@/layouts/MainLayout.vue')
const HomePage = () => import('@/views/HomePage.vue')
const Dashboard = () => import('@/views/Dashboard.vue')
const UserManagement = () => import('@/views/UserManagement.vue')
const PatientManagement = () => import('@/views/PatientManagement.vue')
const AppointmentManagement = () => import('@/views/AppointmentManagement.vue')
const CheckupManagement = () => import('@/views/CheckupManagement.vue')
const CheckupEntry = () => import('@/views/CheckupEntry.vue')
const ReportManagement = () => import('@/views/ReportManagement.vue')
const Profile = () => import('@/views/Profile.vue')
const NotFound = () => import('@/views/NotFound.vue')

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/',
    component: MainLayout,
    redirect: '/home',
    meta: {
      requiresAuth: true
    },
    children: [
      // 首页
      {
        path: 'home',
        name: 'HomePage',
        component: HomePage,
        meta: {
          title: '首页',
          icon: 'HomeFilled'
        }
      },
      // 档案管理模块
      {
        path: 'archives/personal',
        name: 'PersonalArchives',
        component: PatientManagement,
        meta: {
          title: '个人档案管理',
          icon: 'User'
        }
      },
      {
        path: 'archives/group',
        name: 'GroupArchives',
        component: UserManagement,
        meta: {
          title: '团体档案管理',
          icon: 'UserFilled'
        }
      },
      {
        path: 'archives/search',
        name: 'ArchiveSearch',
        component: Dashboard,
        meta: {
          title: '档案查询',
          icon: 'Search'
        }
      },
      // 体检管理模块
      {
        path: 'checkup/appointment',
        name: 'AppointmentManagement',
        component: AppointmentManagement,
        meta: {
          title: '预约管理',
          icon: 'Calendar'
        }
      },
      {
        path: 'checkup/entry',
        name: 'CheckupEntry',
        component: CheckupEntry,
        meta: {
          title: '体检录入',
          icon: 'EditPen'
        }
      },
      {
        path: 'checkup/process',
        name: 'CheckupProcess',
        component: CheckupManagement,
        meta: {
          title: '体检流程',
          icon: 'Connection'
        }
      },
      {
        path: 'checkup/report',
        name: 'ReportManagement',
        component: ReportManagement,
        meta: {
          title: '报告管理',
          icon: 'Document'
        }
      },
      {
        path: 'checkup/review',
        name: 'ReportReview',
        component: Dashboard,
        meta: {
          title: '报告审核',
          icon: 'View'
        }
      },
      // 统计管理模块
      {
        path: 'statistics/overview',
        name: 'StatisticsOverview',
        component: Dashboard,
        meta: {
          title: '统计概览',
          icon: 'DataBoard'
        }
      },
      {
        path: 'statistics/analysis',
        name: 'DataAnalysis',
        component: Dashboard,
        meta: {
          title: '数据分析',
          icon: 'TrendCharts'
        }
      },
      {
        path: 'statistics/export',
        name: 'DataExport',
        component: Dashboard,
        meta: {
          title: '数据导出',
          icon: 'Download'
        }
      },
      // 科室管理模块
      {
        path: 'department/manage',
        name: 'DepartmentManage',
        component: Dashboard,
        meta: {
          title: '科室管理',
          icon: 'OfficeBuilding'
        }
      },
      {
        path: 'department/staff',
        name: 'StaffManage',
        component: UserManagement,
        meta: {
          title: '人员管理',
          icon: 'Avatar'
        }
      },
      {
        path: 'department/equipment',
        name: 'EquipmentManage',
        component: Dashboard,
        meta: {
          title: '设备管理',
          icon: 'Monitor'
        }
      },
      // 体检套餐模块
      {
        path: 'package/manage',
        name: 'PackageManage',
        component: Dashboard,
        meta: {
          title: '套餐管理',
          icon: 'Box'
        }
      },
      {
        path: 'package/items',
        name: 'CheckupItems',
        component: Dashboard,
        meta: {
          title: '检查项目',
          icon: 'List'
        }
      },
      {
        path: 'package/pricing',
        name: 'PricingManage',
        component: Dashboard,
        meta: {
          title: '价格管理',
          icon: 'Money'
        }
      },
      // 系统管理模块
      {
        path: 'system/users',
        name: 'UserManagement',
        component: UserManagement,
        meta: {
          title: '用户管理',
          icon: 'User',
          roles: ['admin']
        }
      },
      {
        path: 'system/roles',
        name: 'RoleManagement',
        component: Dashboard,
        meta: {
          title: '角色管理',
          icon: 'UserFilled',
          roles: ['admin']
        }
      },
      {
        path: 'system/config',
        name: 'SystemConfig',
        component: Dashboard,
        meta: {
          title: '系统配置',
          icon: 'Setting',
          roles: ['admin']
        }
      },
      {
        path: 'system/logs',
        name: 'SystemLogs',
        component: Dashboard,
        meta: {
          title: '操作日志',
          icon: 'Document',
          roles: ['admin']
        }
      },
      // 个人资料
      {
        path: 'profile',
        name: 'Profile',
        component: Profile,
        meta: {
          title: '个人资料',
          icon: 'Setting'
        }
      },
      // 兼容旧路由
      {
        path: 'dashboard',
        redirect: '/archives/personal'
      },
      {
        path: 'users',
        redirect: '/system/users'
      },
      {
        path: 'patients',
        redirect: '/archives/personal'
      },
      {
        path: 'appointments',
        redirect: '/checkup/appointment'
      },
      {
        path: 'checkups',
        redirect: '/checkup/process'
      },
      {
        path: 'reports',
        redirect: '/checkup/report'
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound,
    meta: {
      title: '页面未找到'
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 公共卫生体检系统` : '公共卫生体检系统'
  
  // 检查是否需要认证
  if (to.meta.requiresAuth !== false) {
    const token = localStorage.getItem('token')
    const userInfo = localStorage.getItem('userInfo')
    
    if (!token || !userInfo) {
      ElMessage.warning('请先登录')
      next('/login')
      return
    }
    
    // 检查角色权限
    if (to.meta.roles) {
      const user = JSON.parse(userInfo)
      if (!to.meta.roles.includes(user.role)) {
        ElMessage.error('权限不足，无法访问该页面')
        next('/dashboard')
        return
      }
    }
  }
  
  // 如果已登录用户访问登录页，重定向到仪表盘
  if (to.path === '/login') {
    const token = localStorage.getItem('token')
    if (token) {
      next('/dashboard')
      return
    }
  }
  
  next()
})

// 路由错误处理
router.onError((error) => {
  console.error('路由错误:', error)
  ElMessage.error('页面加载失败，请刷新重试')
})

export default router